﻿using DataManageSystem.Models;
using DataManageSystem.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HeartbeatController : ControllerBase
    {
        private readonly HeartbeatService _heartbeatService;

        public HeartbeatController(HeartbeatService heartbeatService)
        {
            _heartbeatService = heartbeatService;
        }

        [HttpPost]
        public IActionResult Post([FromBody] HeartbeatRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.SystemId))
            {
                return BadRequest("SystemId 不能为空");
            }

            _heartbeatService.Update(request.SystemId);
            Console.WriteLine($"[{DateTime.Now}] 收到来自 {request.SystemId} 的心跳，IP: {request.Ip}");
            return Ok(new { msg = "心跳已记录" });
        }

        [HttpGet("status")]
        public IActionResult GetStatus()
        {
            var timeout = TimeSpan.FromMinutes(1);
            var statusList = _heartbeatService.GetStatus(timeout);

            var result = statusList.Select(s => new
            {
                systemId = s.SystemId,
                lastSeen = s.LastSeen,
                isOnline = s.IsOnline
            });

            return Ok(result);
        }
    }
}
